package hd.util.sqlite;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * SQLite
 * <p/>
 * Created by Haidy on 14/11/22.
 */
public abstract class SQLiteHelper extends SQLiteOpenHelper {

    public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    /**
     * 获取表中项目的数量
     *
     * @param tableName 表的名称
     * @return 表的个数
     */
    public int getTableItemCount(String tableName) {
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.rawQuery("select count(*) from " + tableName, null);
        int count = 0;
        if (c.moveToFirst()) {
            count = c.getInt(0);
        }
        c.close();
        return count;
    }

    /**
     * 删除一个表
     *
     * @param tableName 表名
     */
    public void deleteTable(String tableName) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("delete from " + tableName);
        db.close();
    }

    /**
     * 判断某张表是否存在
     *
     * @param tableName 表名
     * @return true or false
     */
    public boolean tableIsExist(String tableName) {
        boolean result = false;
        SQLiteDatabase db = null;
        Cursor cursor;
        try {
            db = this.getReadableDatabase();
            String sql = "select count(*) as c from sqlite_master  where type ='table' and name ='" + tableName.trim() + "'";
            cursor = db.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    cursor.close();
                    result = true;
                }
            }
        } catch (Exception ignored) {
        }
        if (db != null) {
            db.close();
        }
        return result;
    }

}
